package org.jsoncrypto;

import java.security.SecureRandom;

import javax.crypto.SecretKey;

import org.json.JSONObject;
import org.jsoncrypto.util.Base64;

public class JweAesKW extends JcLibJwe_SK {
  public JweAesKW(JcLibEnc enc, String algStr) throws JcBaseException {
    super(enc, algStr);
  }

  public JweAesKW(String encrypted) throws JcBaseException {
    super(encrypted);
  }

  @Override
  String encrypt(byte[] contentBytes, SecretKey aKey) throws JcBaseException {
    return JcBase.encrypt(contentBytes, mEnc.mHeaderStr, aKey, new SecureRandom());
  }
  
  @Override
  byte[] decrypt(SecretKey key) throws JcBaseException {
    try {
      String encodedJwtHeaderSegment = mEnc.mEncodedJwtHeaderSegment;
      String encodedJwtKeySegment = mEnc.mEncodedJwtKeySegment;
      String encodedJwtIvSegment = mEnc.mEncodedJwtIvSegment;
      String encodedJwtCryptoSegment = mEnc.mEncodedJwtCryptoSegment;
      byte[] jwtIntegritySegmentBytes = Base64
          .decodeUrl(mEnc.mEncodedJwtIntegritySegment);
      JSONObject header = mEnc.mHeader;
      byte[] secretKeyBytes;
      secretKeyBytes = JcBase.unwrapKey(key, encodedJwtKeySegment,
          mEnc.mHeader.getString("alg"));
      return JcBase.doDecrypt(encodedJwtHeaderSegment,
          encodedJwtKeySegment, encodedJwtCryptoSegment,
          jwtIntegritySegmentBytes, header, secretKeyBytes, encodedJwtIvSegment);
    } catch (Exception e) {
      throw new JcBaseException(e);
    }
  }

}
